var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { verifyToken, judgeToken, decodeToken } = require('../../tool/jwt')
const { setDate } = require('../../tool/date')


module.exports = (pool) => {

    //验证token方法
    const tokenvalidate = (req, res, next) => {
        try {
            const token = req.headers.token;
            const v = verifyToken(token, 'shop_key')
            if (v != null) {
                const v2 = judgeToken(token, 'shop_key')
                if (v2 == 0) {
                    next()
                } else {
                    return res.send({ data: { msg: 'token已过期', code: '500' } })
                }

            } else {
                return res.send({ data: { msg: 'token已过期', code: '500' } })
            }

        } catch (error) {
            console.log(error)
            res.status(500).send('Error');
            process.exit(1)
        }
    }
    //获取用户消息列表
    router.get('/newslist', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            // 获取用户信息
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
    
            const connection = await pool.promise().getConnection();
            const result = await connection.query(
                `SELECT newslist.*, user_buy.nickname AS buyer_nickname, user_sell.nickname AS seller_nickname
                 FROM newslist 
                 JOIN user AS user_buy ON user_buy.id = newslist.uid_buy 
                 LEFT JOIN user AS user_sell ON user_sell.id = newslist.uid_sell
                 WHERE newslist.uid_buy = ? OR newslist.uid_sell = ?;`,
                [user.id, user.id]
            );
    
            const newarr = await Promise.all(
                result[0].map(async (item) => {
                    if (item) {
                        try {
                            if (user.id === item.uid_buy) {
                                item.nickname = item.seller_nickname;
                                const [avatarResult] = await connection.query('SELECT avatar FROM user WHERE id = ?', [item.uid_sell]);
                                const [news] = await connection.query('SELECT * FROM news WHERE newslist_id = ? ORDER BY id DESC', [item.id]);
                                item.avatar = avatarResult[0].avatar;
                                item.lastMessage = news.length>0?news[0].content:'还没有消息哦~';
                                item.otherid = item.uid_sell
                            } else {
                                item.nickname = item.buyer_nickname;
                                const [avatarResult] = await connection.query('SELECT avatar FROM user WHERE id = ?', [item.uid_buy]);
                                const [news] = await connection.query('SELECT * FROM news WHERE newslist_id = ? ORDER BY id DESC', [item.id]);
                                item.avatar = avatarResult[0].avatar;
                                item.lastMessage = news.length>0?news[0].content:'还没有消息哦~';
                                item.otherid = item.uid_buy
                            }
                        } catch (error) {
                            console.error('Error processing item:', error);
                            return null; 
                        }
                    }
                    return item; 
                })
            );
            connection.release();
            // console.log(newarr);
            res.send({ data: { msg: '获取成功', code: 200, data: newarr } });
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        } 
    });


    //获取用户对话消息
    router.get('/newsByuser/:id', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const {id} = req.params;
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            const result = await connection.query('SELECT news.*,user.nickname FROM news JOIN user on news.uid = user.id WHERE newslist_id = ?',[id]);
            connection.release();
            res.send({ data: { msg: '获取成功', code: 200, data: result[0] } });
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //获取用户id，socketid
    router.get('/getsocket/:rid',(req, res, next) => { tokenvalidate(req, res, next) },async (req,res)=>{
        try {
            //对方id
            const {rid} = req.params;
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            const result = await connection.query('SELECT socket_id FROM user WHERE id = ?',[rid]);
            connection.release();
            const { socket_id } = result[0][0];
            if(result[0].length == 0) return res.send({ data: { msg: '获取失败', code: 500 } });
            res.send({ data: { msg: '获取成功', code: 200, data: { id:user.id, socket_id } } });
            
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //进程崩溃，关闭数据库连接
    process.on('SIGINT', () => {
        pool.end();
        redis.disconnect();
        process.exit(0);
    })

    //返回路由
    return router

}

